//
//  ForgetPswViewController.m
//  citzenWorkStation
//
//  Created by yang qing on 2018/2/27.
//  Copyright © 2018年 yang qing. All rights reserved.
//

#import "ForgetPswViewController.h"
#import "CommonReqManage.h"
#import "UserInfoBean.h"
#import "CommonReqManage.h"
#import "NSObject+YYModel.h"

@interface ForgetPswViewController () {
    dispatch_source_t _timer;
}
@property (weak, nonatomic) IBOutlet UITextField *tfPhoneNumber;
@property (weak, nonatomic) IBOutlet UITextField *tfMsgCode;
@property (weak, nonatomic) IBOutlet UIButton *btnGetCode;
@property (weak, nonatomic) IBOutlet UITextField *tfSetPsw;
@property (weak, nonatomic) IBOutlet UIButton *btnConfirm;

@end

@implementation ForgetPswViewController
- (void)viewDidLoad {
    [super viewDidLoad];
    [self initView];
    [self initListener];

}

- (void)initListener{
    [self.btnGetCode addTarget:self action:@selector(sendMsgCode) forControlEvents:UIControlEventTouchUpInside];
    [self.btnConfirm addTarget:self action:@selector(confirmClick) forControlEvents:UIControlEventTouchUpInside];
}

- (void)confirmClick{
    if([self checkData]){
        NSString *phoneNumber = _tfPhoneNumber.text;
        NSString *msgCode = _tfMsgCode.text;
        NSString *psw = _tfSetPsw.text;
        UserInfoBean *userInfo = [[UserInfoBean alloc]init];
        userInfo.phoneNumber = phoneNumber;
        userInfo.verifyCode = msgCode;
        userInfo.password = psw;
        id userInfoStr = [userInfo yy_modelToJSONObject];
        [self showHub:@""];
        [CommonReqManage findPsw:userInfoStr success:^(id success) {
            [self hiddenHub];
            NSString *status =  success[@"status"];
            if([status isEqualToString:@"1"]){
                [self showToast:@"修改成功"];
                [self.navigationController popViewControllerAnimated:YES];
            }else{
                [self showTip:success[@"message"] cancelText:@"" confirmText:@"确定" Confirm:nil Cancel:nil];
            }
        } failed:^(id faiure) {
            [self hiddenHub];
            [self showHubAuto:@"请求失败"];
        }];
    }
   
}

- (void)sendMsgCode{
    //请求网络发送验证码
    if([_tfPhoneNumber.text isEqualToString:@""]){
        [self showToast:@"请输入手机号"];
        return;
    }
    
    [CommonReqManage getMesgCode:_tfPhoneNumber.text success:^(id success) {
        NSString *status =  success[@"status"];
        if([status isEqualToString:@"1"]){
            [self countDown];
        }else{
             [self showTip:success[@"message"] cancelText:@"" confirmText:@"确定" Confirm:nil Cancel:nil];
        }
    } failed:^(id failure) {
        NSLog(@"failur");
        [self showHubAuto:@"请求失败"];
    }];
}
- (void)countDown{
    __block int timeout=59; //倒计时时间
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
     _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0,queue);
    dispatch_source_set_timer(_timer,dispatch_walltime(NULL, 0),1.0*NSEC_PER_SEC, 0); //每秒执行
    dispatch_source_set_event_handler(_timer, ^{
        if(timeout<=0){ //倒计时结束，关闭
            dispatch_source_cancel(_timer);
            dispatch_async(dispatch_get_main_queue(), ^{
                [_btnGetCode setTitle:@"发送验证码" forState:UIControlStateNormal];
                //设置不可点击
                _btnGetCode.userInteractionEnabled = YES;
            });
        }else{
            int seconds = timeout % 60;
            NSString *strTime = [NSString stringWithFormat:@"%d", seconds];
            dispatch_async(dispatch_get_main_queue(), ^{
                //设置界面的按钮显示 根据自己需求设置
                NSLog(@"____%@",strTime);
                [_btnGetCode setTitle:[NSString stringWithFormat:@"重新发送(%@)",strTime] forState:UIControlStateNormal];
                //设置可点击
                _btnGetCode.userInteractionEnabled = NO;
            });
            timeout--;
        }
    });
    dispatch_resume(_timer);
}


- (void)initView{
    self.navigationController.navigationBar.tintColor = [UIColor whiteColor];
    self.navigationItem.title = self.titleName;
    [self tfAddLeftImg:_tfPhoneNumber ImageName:@"icon_phone"];
       _tfPhoneNumber.keyboardType = UIKeyboardTypePhonePad;
    [self tfAddLeftImg:_tfMsgCode ImageName:@"icon_code"];
    _tfMsgCode.keyboardType = UIKeyboardTypeNumberPad;
    [self tfAddLeftImg:_tfSetPsw ImageName:@"icon_pwd"];
   _tfSetPsw.secureTextEntry=YES;
    
    //设置按钮边框
    [_btnGetCode.layer setMasksToBounds:YES];
    [_btnGetCode.layer setBorderWidth:1.0];
    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
    CGColorRef color = CGColorCreate(colorSpace, (CGFloat[]){ 88/255.0, 158/255.0, 248/255.0, 1 });
    [_btnGetCode.layer setBorderColor:color];
    _btnGetCode.contentEdgeInsets = UIEdgeInsetsMake(8, 10, 8, 10);
    
}

//添加左侧图标
- (void)tfAddLeftImg:(UITextField *)textField ImageName:(NSString *)imageName{
    textField.leftViewMode = UITextFieldViewModeAlways;
    UIImageView *phoneImage = [[UIImageView alloc]initWithImage:[UIImage imageNamed:imageName]];
    [phoneImage setFrame:CGRectMake(10, 5, 30, 30)];
    UIView *lv = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 40, 40)];
    textField.center = lv.center;
    [lv addSubview:phoneImage];
    textField.leftView = lv;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}


- (void)viewDidDisappear:(BOOL)animated{
    [super viewDidDisappear:animated];
    if(_timer!=nil){
        dispatch_source_cancel(_timer);
    }
}

- (BOOL)checkData{
    if([_tfPhoneNumber.text isEqualToString:@""]){
          [self showToast:@"请输入手机号"];
        return NO;
    }
    if([_tfMsgCode.text isEqualToString:@""]){
          [self showToast:@"请输入验证码"];
        return NO;
    }
    if([_tfSetPsw.text isEqualToString:@""]){
          [self showToast:@"请输入密码"];
        return NO;
    }
    
    
    return YES;
}






@end
